package dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import model.Friendship;
import model.IEntity;
import model.User;

public class FriendDAO implements IDAO
{
	SqlSessionFactory sqlSessionFactory;

	public FriendDAO()
	{
		try
		{
			String resource = "conf.xml";

			InputStream is = Resources.getResourceAsStream(resource);

			sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean addOne(IEntity e)
	{
		SqlSession session = sqlSessionFactory.openSession();
		int count = session.insert("mapper.friendshipMapper.addOne", (Friendship)e);
		session.commit();
		if(count>0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@Override
	public boolean deleteOne(IEntity e)
	{
		
		SqlSession session = sqlSessionFactory.openSession();
		int count = session.delete("mapper.friendshipMapper.deleteOne", (Friendship)e);
		session.commit();
		if(count>0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@Override
	public boolean updateOne(IEntity e)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public IEntity getOne(IEntity e)
	{
		SqlSession session = sqlSessionFactory.openSession();
		Friendship fs = session.selectOne("mapper.friendshipMapper.getOne", (Friendship)e);
		return fs;
	}

	@Override
	public List<IEntity> getList(IEntity e)
	{
		String phoneA = ((Friendship)e).getPhoneA();
		if(phoneA==null)
		{
			return null;
		}
		SqlSession session = sqlSessionFactory.openSession();
		List<IEntity> friends = session.selectList("mapper.friendshipMapper.getList", phoneA);
		return friends;
	}

}
